import { Component, OnInit, Injector, Output, EventEmitter } from '@angular/core';
import { ServiceProxy, SiteDTO, UserInfoDTO, WarnInfoDTO } from '@shared/service-proxy/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-send-message-modal',
  templateUrl: './send-message-modal.component.html',
  styleUrls: ['./send-message-modal.component.less']
})
export class SendMessageModalComponent extends AppComponentBase implements OnInit {
  @Output() modalSave = new EventEmitter<any>();
  isVisible: boolean = false;
  isOkLoading: boolean = false;
  model = { id: "", phone: "", siteId: "", userId: "" ,msg:""};
  sites: SiteDTO[];
  users: UserInfoDTO[] = [];
  totalUsers: UserInfoDTO[] = [];

  validateForm: FormGroup;
  constructor(injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      siteId: [null, [Validators.required]],
      userId: [null, [Validators.required]],
      phone: [null, [Validators.required]],
      msg:[null, [Validators.required]],
    });

    this.getSites();
    this.getUsers();
  }

  getSites() {
    this._service.getAllSitesBySiteUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    })
  }

  getUsers() {
    this._service.getAllUserInfoListUsingGET().subscribe(result => {
      this.totalUsers = result.result.fieldList;
    })
  }

  getSiteForUser() {
    this.users = this.totalUsers.filter(m => m.siteId == this.model.siteId);
  }

  getPhone() {
    const user = this.users.find(m => m.id == this.model.userId);
    if (user)
      this.model.phone = user.phone;
  }

  handleOk() {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {

      this._service.sendMessageUsingGET(this.model.id, this.model.phone,this.model.msg).subscribe(result => {
        this.isOkLoading = false;
        if (result.success) {
          this.message.success(this.l('send_success'));
          this.handleCancel()
        } else {
          this.message.error(this.l('notify_failed'));
        }
      })
    }
    else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }
  handleCancel() {
    this.isVisible = false;
    this.modalSave.emit();
  }

  show(info:any) {
    this.isVisible = true;
    this.model.id = info.id;
    this.model.phone = "";
    this.model.msg = this.l("lockset_no")+this.l(info.lockCode) +"/"+
     this.l("lockset")+this.l("state")+":"+ info.msg+"/"+this.l("warn_date_time")+":"+ info.creationTime;
  }
}
